package com.yy.permissions_general.base.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yy.permissions_general.module.system.aopLog.mapper.SysLogMapper;
import com.yy.permissions_general.module.system.history.entity.History;
import com.yy.permissions_general.module.system.history.mapper.HistoryMapper;
import com.yy.permissions_general.utils.FTP;
import com.yy.permissions_general.utils.monitor.CpuInfo;
import com.yy.permissions_general.utils.monitor.SystemUtil;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 共用前端控制器
 * @Author: YY
 * @Date: 2021/3/14
 */
@Controller
public class BaseController {

    public Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    protected SysLogMapper sysLogMapper;

    @Resource
    protected HistoryMapper historyMapper;

    @Resource
    protected HttpServletRequest request;

    @Resource
    protected HttpSession session;

    /**
     * @MethodName: main
     * @Description: TODO 获取系统参数信息
     * @Param: [model]
     * @Return: org.springframework.web.servlet.ModelAndView
     * @Author: YangYI
     * @Date: 2022/2/15
    **/
    @GetMapping("/monitor/findMonitor")
    @PreAuthorize("hasPermission('/monitor/findMonitor','')")
    public ModelAndView main(Model model) {
        CpuInfo cpu = SystemUtil.getCpu();
        model.addAttribute("cpu", cpu);
        return jumpPage("system/monitor/findMonitor");
    }

    /**
     * @Description: html访问控制器
     * @Author: YY
     * @Date: 2021/3/15
     */
    @GetMapping(value = "/view/**")
    public ModelAndView html(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(StrUtil.removePrefix(request.getRequestURI(), request.getContextPath() + "/view"));
        return modelAndView;
    }

    /**
     * @MethodName: downloadFile
     * @Description: TODO 附件下载
     * @Param: [response, url, fileName, suffix]
     * @Return: void
     * @Author: YangYI
     * @Date: 2022/1/6
     **/
    @RequestMapping("/downloadFile")
    public void downloadFile(HttpServletResponse response, String filePath, String fileName, String suffix) throws Exception {
        FTPClient ftp = new FTPClient();
        try {
            //设置文件ContentType类型 "application/form-data，这样设置，会自动判断下载文件类型
            response.setContentType("application/octet-stream;charset=ISO_8859_1");
            //设置Content-Disposition
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO_8859_1");
            ftp.connect(FTP.ip);
            ftp.login(FTP.username, FTP.password);// 登录
            ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode();
            ftp.setBufferSize(1024 * 1024);
            InputStream is = ftp.retrieveFileStream(filePath);
            if (is != null) {
                OutputStream out = response.getOutputStream();
                response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                    out.flush();
                }
                if (out != null) {
                    out.close();
                }
                if (is != null) {
                    is.close();
                }
            } else {
                response.setContentType("text/html;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                writer.write("<script>alert('文件不存在~');history.back()</script>");
            }
        } catch (Exception e) {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write("<script>alert('下载失败~');history.back()</script>");
        } finally {
            ftp.logout();
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }

    /**
     * @MethodName: welcome
     * @Description: TODO 首页
     * @Param: []
     * @Return: org.springframework.web.servlet.ModelAndView
     * @Author: YangYI
     * @Date: 2022/2/15
    **/
    @GetMapping("/welcomePage")
    public ModelAndView welcome() {
        Integer todayNum = sysLogMapper.getAccessNum(1);
        Integer weekNum = sysLogMapper.getAccessNum(2);
        Integer monthNum = sysLogMapper.getAccessNum(3);
        Integer quarterNum = sysLogMapper.getAccessNum(4);
        Map<String,Object> objMap = sysLogMapper.getAccessRecord();
        Page page = new Page(0,10);
        Page<History> selectPage = historyMapper.selectPage(page,new History());
        Map<String,Object> map = new HashMap<>();
        map.put("todayNum", ObjectUtil.isEmpty(todayNum) ? 0 : todayNum);
        map.put("weekNum", ObjectUtil.isEmpty(weekNum) ? 0 : weekNum);
        map.put("monthNum", ObjectUtil.isEmpty(monthNum) ? 0 : monthNum);
        map.put("quarterNum", ObjectUtil.isEmpty(quarterNum) ? 0 : quarterNum);
        map.put("category", ObjectUtil.isEmpty(objMap.get("category")) ? "[]": Convert.toStr(objMap.get("category")).split(","));
        map.put("initValue", ObjectUtil.isEmpty(objMap.get("initValue")) ? "[]" :Convert.toStr(objMap.get("initValue")).split(","));
        map.put("histories", selectPage.getRecords());
        return jumpPage("welcome",map);
    }
    /**
     * 页面跳转
     */
    public ModelAndView jumpPage(String path) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(path);
        return modelAndView;
    }

    /**
     * 带参数的页面跳转
     */
    public ModelAndView jumpPage(String path, Map<String, ?> params) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(path);
        modelAndView.addAllObjects(params);
        return modelAndView;
    }

    /**
     * 不能自动注入，下文使用ModelAttribute注入
     */
    private static final ThreadLocal<HttpServletResponse> responseContainer = new ThreadLocal<HttpServletResponse>();


    @ModelAttribute
    private void initResponse(HttpServletResponse response) {
        responseContainer.set(response);
    }

    /**
     * 获取当前线程的response对象
     *
     * @return
     */
    protected final HttpServletResponse getResponse() {
        return responseContainer.get();
    }


}
